local socket = require "socket"

local M = {}

M.state = {
    phase_id = -1,
    _countdown_value = 0,
    _countdown_begin_at = 0,
    result_view = nil,
    payout_detail = nil,
    bet_history = {},
    current_round_history = {},
    scene = nil,
    records = {}
}

M.getters = {
    -- 倒计时剩余秒数
    countdown = function(state)
        local elapsed = socket.gettime() - state._countdown_begin_at
        local ret = state._countdown_value / 1000 - elapsed
        return ret
    end
}

M.mutations = {
    init = function(store, state, args)
        state.scene = args
        state.records = args.records
        store.emit("恢复游戏场景")
    end,

    set_phase = function(store, state, args)
        state.phase_id = args.phase_id
        state._countdown_begin_at = socket.gettime()
        state._countdown_value = args.countdown

        if args.phase_id == 2 then
            -- TODO:换成mutations
            state.bet_history = state.current_round_history
            state.current_round_history = {}
        end
        
        store.emit("阶段变更")
    end,

    set_player_chip = function(store, state, args)
        local player = args.player
        player.old_chip = args.old

        store.emit("筹码变更", args)
    end,

    player_bet = function(store, state, args)
        local player = args.player
        local area_id = args.area_id
        local amount = args.amount
        store.emit("玩家下注", args)
    end,

    reveal = function(store, state, args)
        local view = args.view
        local payout_detail = args.payout_detail
        state.result_view = view
        state.payout_detail = payout_detail
        table.insert(state.records, view)
        store.emit("展示结果")
        store.emit("增加游戏记录")
    end,

    record_bet_history = function(store, state, args)
        local id = args.id
        local amount = args.amount
        table.insert(state.current_round_history, {id = id, amount = amount})
    end,

    sync_record = function(store, state, views)
        state.records = views
        store.emit('同步游戏记录')
    end
}

return M